package com.joker.demo.core.netty.client.handler;

import com.joker.demo.core.netty.server.handler.HttpServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 消息类型检测器
 * 由于不再使用HTTP请求，此类现在只处理自定义协议消息
 *
 * @author Joker
 * @since 2025-07-26
 */
public class ClientProtocolRouterHandler extends ByteToMessageDecoder {

    private static final Logger log = LoggerFactory.getLogger(ClientProtocolRouterHandler.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }

        in.markReaderIndex();

        if (isHttpRequest(in)) {
            log.debug("检测到HTTP请求");
            in.resetReaderIndex();
            // 重新插入HTTP处理器
            ChannelPipeline p = ctx.pipeline();
            p.addAfter(ctx.name(), "http-codec", new HttpServerCodec());
            p.addAfter("http-codec", "aggregator", new HttpObjectAggregator(65536));
            p.addAfter("aggregator", "http-handler", new HttpServerHandler());
            p.remove(this);

            // 重新触发处理
            ctx.fireChannelRead(in.retain());
        } else {
            log.debug("检测到自定义协议消息");
            in.resetReaderIndex();
            ctx.pipeline().remove(this);
        }
    }

    /**
     * 检测是否为HTTP请求
     * HTTP请求通常以HTTP方法开头（GET, POST, PUT, DELETE等）
     */
    private boolean isHttpRequest(ByteBuf in) {
        // 检查前几个字节是否为HTTP方法
        byte[] bytes = new byte[Math.min(in.readableBytes(), 10)];
        in.getBytes(in.readerIndex(), bytes);
        String start = new String(bytes).toUpperCase();

        return start.startsWith("GET ") ||
                start.startsWith("POST ") ||
                start.startsWith("PUT ") ||
                start.startsWith("DELETE ") ||
                start.startsWith("HEAD ") ||
                start.startsWith("OPTIONS ") ||
                start.startsWith("PATCH ");
    }
} 